package com.sskj.login;

import java.util.Random;
import org.ehcache.Cache;
import org.ehcache.CacheManager;
import org.ehcache.config.CacheConfiguration;
import org.ehcache.config.builders.CacheConfigurationBuilder;
import org.ehcache.config.builders.CacheManagerBuilder;
import org.ehcache.config.builders.ResourcePoolsBuilder;
import org.ehcache.expiry.Duration;
import org.ehcache.expiry.Expirations;
import static java.util.concurrent.TimeUnit.MINUTES;

public class VerificationCodeGenerator {

    /**
     * 缓存名称
     */
    private static final String CACHE_NAME = "verificationCodeCache";
    /**
     * 验证码有效时间 单位：分
     */
    private static final int EXPIRATION_MINUTES = 3;
    /**
     * 验证码长度
     */
    private static final int CODE_LENGTH = 4;
    
    private static Cache<String, String> verificationCodeCache;
    
    static {
        // 配置 Ehcache 缓存
        CacheConfiguration<String, String> cacheConfiguration = CacheConfigurationBuilder.newCacheConfigurationBuilder(
            String.class,
            String.class,
            ResourcePoolsBuilder.heap(100))
            .withExpiry(Expirations.timeToLiveExpiration(Duration.of(EXPIRATION_MINUTES, MINUTES)))
            .build();
        CacheManager cacheManager = CacheManagerBuilder.newCacheManagerBuilder().build();
        cacheManager.init();
        verificationCodeCache = cacheManager.createCache(CACHE_NAME, cacheConfiguration);
    }

    /**
     * 生成验证码
     * @param key
     * @return
     */
    public static String generateCode(String key) {
        // 生成 4 位随机验证码
        Random random = new Random();
        StringBuilder code = new StringBuilder();
        for (int i = 0; i < CODE_LENGTH; i++) {
            code.append(random.nextInt(10));
        }
        // 将验证码存储到 Ehcache 缓存中，使用 key 作为缓存键
        verificationCodeCache.put(key, code.toString());
        return code.toString();
    }

    /**
     * 校验验证码
     * @param key
     * @param code
     * @return
     */
    public static boolean verifyCode(String key, String code) {
        // 从 Ehcache 缓存中获取验证码，并与传入的验证码进行比较
        String cachedCode = verificationCodeCache.get(key);
        return cachedCode != null && cachedCode.equals(code);
    }
}
